package com.sun.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.pojo.Blog;
import com.sun.pojo.Comment;
import com.sun.service.BlogService;
import com.sun.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author: glorysun
 * @date: 2020/8/17
 */
@Controller
@RequestMapping("/admin")
public class CommentsController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;


    //留言列表页
    @GetMapping("/comments")
    public String comments(Model model, HttpSession session,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum) {

        PageHelper.startPage(pageNum, 3);    //***要放在需要分类的查询语句之前！！！！！！！
        List<Blog> blogList=blogService.selectBlogListByComment();

        //遍历blog集合
        for(int i=0;i<blogList.size();i++){
            List<Comment> comments=commentService.selectCommentByBlogId(blogList.get(i).getId());
            if(comments.size()==0){
                blogList.remove(i);
                i--;
            } else{
                blogList.get(i).setComments(comments);
            }
        }
        System.out.println(blogList);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("pageInfo", pageInfo);

        return "/admin/comments";
    }

    @PostMapping("/commentReply")
    public String reply(Comment comment){
        comment.setAvatar(avatar);
        commentService.insertComment(comment);
        return "redirect:/admin/comments";
    }

}

